<template>
  <div class="flex justify-between items-center mb-4">
    <h2 class="text-xl font-bold">作业管理</h2>
    <el-button type="primary" @click="emits('publish')"> 发布作业 </el-button>
  </div>
  <el-table :data="homeworks" style="width: 100%">
    <el-table-column prop="des" label="作业描述" />
    <el-table-column prop="courseName" label="所属课程" />

    <el-table-column prop="files" label="附件">
      <template #default="{ row }: { row: HomeworkProp }">
        <div v-for="file in row.files" :key="file.fileUrl">
          <span class=" text-blue-500 cursor-pointer" @click="downloadHomework(file.fileUrl)">{{ file.name }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="createdTime" label="创建时间" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button type="primary" @click="showUpdateDialog(row)">
          修改
        </el-button>
        <el-button type="danger" @click="deleteTask(row.id)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="showUpdate" title="修改作业" width="500px">
    <el-form :model="updateHomework" label-width="80px">
      <el-form-item label="作业描述" prop="des" :rules="{ required: true, message: '请输入作业描述', trigger: 'blur' }">
        <el-input v-model="updateHomework.des" placeholder="请输入作业描述"></el-input>
      </el-form-item>
      <el-form-item label="附件">
        <div v-if="updateHomework.files.length > 0" class="flex items-center justify-between w-full">
          <span class=" text-blue-500 cursor-pointer" @click="downloadHomework(updateHomework.files[0].fileUrl)">{{
            updateHomework.files[0].name }}</span>
          <el-button type="text" @click="updateHomework.files = []">删除</el-button>
        </div>
        <el-button v-else type="primary" @click="handleUpload">上传附件</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="updateTaskById()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  getHomeworkById,
  deleteTaskById,
  updateTask,
} from "../../../api/modules/course";
import { downloadFile } from "../../../api/modules/file";
import { useUserStore } from "../../../store/user";
import { request } from "../../../utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

function downloadHomework(url?: string) {
  if (!url) return;
  downloadFile(url).then((res) => {
    const blob = new Blob([res as any]);
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = url;
    link.click();
  });
}
const emits = defineEmits<{
  publish: [];
  upload: [];
}>();
// 作业列表
const homeworks = ref([]);
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo.value);


interface HomeworkProp {
  id: string,
  des: string,
  files: { file: File, fileUrl: string, name: string }[],
}
const updateHomework = ref<HomeworkProp>({
  id: "",
  des: "",
  files: [],
});
const showUpdate = ref(false);
function getHomework() {
  if (!userInfo.value) return;
  const id = userInfo.value.id;
  request({
    fn: getHomeworkById,
    params: [id],
    success(res) {
      homeworks.value = res.data || [];
    },
  });
}
function cancel() {
  showUpdate.value = false;
  if (!updateHomework.value) return;
  updateHomework.value.id = "";
  updateHomework.value.des = "";
  updateHomework.value.files = [];
}

function showUpdateDialog(data) {
  showUpdate.value = true;
  console.log(data);
  if (!updateHomework.value) return;
  updateHomework.value.des = data.des;
  updateHomework.value.id = data.id;
  updateHomework.value.files = data.files || [];
}
function updateTaskById() {
  const formData = new FormData();
  if (!updateHomework.value) return;
  formData.append("id", updateHomework.value.id);
  if (updateHomework.value.files?.[0]) {
    formData.append("file", updateHomework.value.files[0].file);
  }
  formData.append("des", updateHomework.value.des);


  request({
    fn: updateTask,
    params: [formData],
    success() {
      ElMessage.success("提交成功");
      if (!updateHomework.value) return;
      updateHomework.value.des = "";
      updateHomework.value.id = "";
      updateHomework.value.files = [];
      showUpdate.value = false;
      getHomework();
    },
  });
}

function deleteTask(id) {
  ElMessageBox.confirm("是否删除该课程", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    type: "warning",
  }).then(() => {
    request({
      fn: deleteTaskById,
      params: [id],
      success(res) {
        ElMessage.success("删除成功");
        getHomework();
      },
    });
  });
}

function handleUpload() {
  const input = document.createElement("input");
  input.type = "file";
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file && updateHomework.value) {
      const url = URL.createObjectURL(file);
      updateHomework.value.files.push({
        file: file,
        fileUrl: url,
        name: file.name,
      });
    }

  };
  input.click();
}


getHomework();

defineExpose({
  getHomework,
});
</script>
<style scoped lang="scss"></style>
